﻿using MediatR;
using MES.Bom.API.Application.Command.BOM命令;
using MES.Bom.Domain;
using MES.Bom.Dto;
using MES.Bom.ErrorCode;
using MES.Bom.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace MES.Bom.API.Application.CommandHandler.BOM命令处理
{
    public class BomQueryCommandHandler : IRequestHandler<BomQueryCommand, APIResult<APIPaging<BomGoodsDto>>>
    {
        private readonly IBaseRepository<Boms> bomRepository;
        private readonly IBaseRepository<Goods> goodsRepository;
        public BomQueryCommandHandler(IBaseRepository<Boms> bomRepository, IBaseRepository<Goods> goodsRepository = null)
        {
            this.bomRepository = bomRepository;
            this.goodsRepository = goodsRepository;
        }

        public Task<APIResult<APIPaging<BomGoodsDto>>> Handle(BomQueryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<APIPaging<BomGoodsDto>> result = new APIResult<APIPaging<BomGoodsDto>>();
                var list = bomRepository.GetValues().AsNoTracking();
                if (!string.IsNullOrEmpty(request.BomCode)) 
                {
                    list = list.Where(x => x.BomCode == request.BomCode);
                }


                var res = from a in list
                          join b in goodsRepository.GetValues().AsNoTracking()
                          on a.GoodsId equals b.ID
                          select new BomGoodsDto
                          {
                              ID = a.ID,
                              BomCode = a.BomCode,
                              BomTopic = a.BomTopic,
                              BomVersion = a.BomVersion,
                              IsDefaultBom = a.IsDefaultBom,
                              GoodsId = a.GoodsId,
                              DayPlannum = a.DayPlannum,
                              Note = a.Note,
                              GoodsCode = b.GoodsCode,
                              GoodsName = b.GoodsName,
                              GoodsType = b.GoodsType,
                              GoodsStatus = b.GoodsStatus,
                              Oneprice = b.Oneprice,
                              CreateTime = a.CreateTime,
                          };

                APIPaging<BomGoodsDto> paging = new APIPaging<BomGoodsDto>();
                paging.TotalCount = res.Count();
                paging.TotalPages = (int)Math.Ceiling(paging.TotalCount * 1.0 / request.PageSize);
                paging.List=res.OrderByDescending(x=>x.CreateTime).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize).ToList();
                result.Code = APIEnums.Success;
                result.Message = "获取成功";
                result.Data = paging;
                return Task.FromResult(result);
            }
            catch (Exception ex)
            {

                throw;
            }
        }
    }
}
